package com.qf.listener;

import com.qf.controller.ItemController;
import com.qf.entity.Goods;
import freemarker.core.ParseException;
import freemarker.template.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 刘亚康
 * @Date 2020/4/6
 * @Version 1.0'
 * @Description
 */
@Component
@Slf4j
public class ItemQueueListemer {
    @Autowired
    private Configuration configuration;

    @RabbitListener(queues = "itemQueue")
    public void reciveQueue(Goods goods){
        log.info("itemQueue队列收到消息："+goods);
        //获取商品图片集合
        String[] goodsPicList = goods.getGoodsPic().split("\\|");
        //写入流
        Writer writer=null;
        try {
            //获取模板
            Template template = configuration.getTemplate("goodsItem.ftl");
            //获取商品输出路径目录
            String staticPath = ItemController.class.getClassLoader().getResource("static").getPath();
            File file = new File(staticPath + File.separator + "goodsPage");
            //判断目录是否存在
            if (!file.exists()) {
                file.mkdir();
            }

            Map<Object,Object> map=new HashMap<>();
            map.put("goods",goods);
            map.put("goodsPicList",goodsPicList);
            map.put("contextPath","/");
            writer=new FileWriter(file.getAbsoluteFile()+File.separator+goods.getGoodsId()+".html");

            //输出到文件
            template.process(map,writer);

        } catch (ParseException e) {
            e.printStackTrace();
        } catch (MalformedTemplateNameException e) {
            e.printStackTrace();
        } catch (TemplateNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
